package com.gin.kotlin.gf2gamecommunity.composable

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.TextUnitType
import androidx.compose.ui.unit.dp
import androidx.core.graphics.toColorInt
import com.gin.kotlin.gf2gamecommunity.R
import com.gin.kotlin.gf2gamecommunity.app.CommentImageShow
import com.gin.kotlin.gf2gamecommunity.base.composable.MyImage
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.nodes.Node
import org.jsoup.nodes.TextNode

/**
 * 渲染一段HTML代码
 * @param T 列表项类型
 * @param item 列表项对象
 * @param html String
 * @param onClickImage 点击图片时的回调
 * @param textStyle TextStyle?
 */
@Composable
fun <T> HtmlText(item: T, html: String, textStyle: TextStyle = TextStyle(), onClickImage: (item: T, url: String) -> Unit = { _, _ -> }) {
    // println("html = $html")
    val document = Jsoup.parse(html).body()
    Row(modifier = Modifier.fillMaxWidth()) {
        SelectionContainer {
            NodesRender(item = item,
                elements = document.childNodes(),
                textStyle = textStyle,
                onClickImage = onClickImage)
        }
    }
}

/**
 * 外层设置的文字style
 * @param node Node
 * @param T 列表项类型
 * @param item 列表项对象
 * @param textStyle TextStyle?
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun <T> NodeRender(item: T, node: Node, textStyle: TextStyle = TextStyle(), onClickImage: (item: T, url: String) -> Unit) {
    val context = LocalContext.current
    // println("node = ${node}")
    if (node is TextNode) {
        Text(node.text(), style = textStyle)
    } else if (node is Element) when (node.tagName()) {
        "p", "div", "hr", "span" -> FlowRow { NodesRender(item, node.childNodes(), textStyle, onClickImage) }
        "br" -> FlowRow { Text(" ", modifier = Modifier.weight(1f)) }
        "b" -> FlowRow { NodesRender(item, node.childNodes(), textStyle.copy(fontWeight = FontWeight.Bold), onClickImage) }
        "strike" -> FlowRow { NodesRender(item, node.childNodes(), textStyle.copy(textDecoration = TextDecoration.LineThrough), onClickImage) }
        "font" -> {
            val size = node.attr("size").toIntOrNull()
            val color = node.attr("color").takeIf { it.isNotEmpty() }?.toColorInt()?.let { Color(it) }

            val style = textStyle.copy(fontSize = size?.let { TextUnit(it.toFloat(), TextUnitType.Em) } ?: textStyle.fontSize, color = color ?: textStyle.color)
            FlowRow { NodesRender(item, node.childNodes(), style, onClickImage) }
        }

        "a" -> {
            Text(text = node.text(), style = textStyle.copy(color = Color.Blue), modifier = Modifier.clickable {
                context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(node.attr("href"))))
            })
        }

        "img" -> {
            val url = node.attr("src")
            when {
                node.hasClass("emoji") -> MyImage(model = url, modifier = Modifier.size(80.dp))

                else -> {
                    // 根据策略决定：显示图片 或 显示占位
                    CommentImageShow { s, _ ->
                        if (s.show(LocalContext.current)) {
                            MyImage(model = url, modifier = Modifier.clickable { onClickImage(item, url) })
                        } else {
                            Column(modifier = Modifier
                                .clickable { onClickImage(item, url) }
                                .size(80.dp), horizontalAlignment = Alignment.CenterHorizontally) {
                                Icon(painterResource(R.drawable.ic_image_24), null, modifier = Modifier.size(48.dp))
                                Text("点击显示")
                            }
                        }
                    }
                }
                // else -> Text(node.toString(), style = textStyle)
            }
        }

        "iframe" -> {
            val httpUrl = node.attr("src").toHttpUrlOrNull()
            when (httpUrl?.host) {
                "player.bilibili.com" -> {
                    val bvId = httpUrl.queryParameter("bvid")
                    if (!bvId.isNullOrBlank()) {
                        Row(Modifier
                            .fillMaxWidth()
                            .padding(8.dp)) {
                            Button(onClick = {
                                context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://www.bilibili.com/video/$bvId")))
                            }) {
                                Text("跳转到Bilibili", style = textStyle)
                            }
                        }
                    }
                }

                else -> Text(node.toString(), style = textStyle)
            }
        }

        else -> Text(node.toString(), style = textStyle)
    }

}

@Composable
fun <T> NodesRender(item: T, elements: List<Node>, textStyle: TextStyle = TextStyle(), onClickImage: (item: T, url: String) -> Unit) =
    elements.forEach { NodeRender(item, it, textStyle, onClickImage) }